package com.weixin.web;

import com.agent.entity.RepaireInfo;
import com.agent.entity.User;
import com.agent.service.IRepaireInfoService;
import com.agent.service.UserService;
import com.agent.shiro.ShiroUser;
import com.agent.util.Constants;
import com.agent.util.ResponseData;
import com.agent.vo.RepaireInfoVO;
import com.weixin.util.WXUserUtil;
import com.weixin.vo.PickerVO;
import com.weixin.pojo.Textcard;
import com.weixin.pojo.WXMsg;
import com.weixin.service.WeixinNotifyService;
import com.weixin.util.WxepConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.agent.util.ResponseData.getSuccessResult;

/**
 * Created by hg on 2019/1/17.
 */
@RequestMapping(value = "/weixin/allocation")
@Controller
@Slf4j
public class AllocationController {
    @Resource(name = "userServiceImpl")
    UserService userService;

    @Resource(name = "repaireInfoService")
    IRepaireInfoService repaireInfoService;

    @Resource(name = "weixinNotifyService")
    WeixinNotifyService weixinNotifyService;
    // 由座席发起的操作
    @RequestMapping(value = "/to_allocation")
    public String to_allocation(Model model,@RequestParam("userId")String userId){
//        if(validateAuth(userId,2)){
            Map<String,String> paramMap = new HashedMap();
            paramMap.put("currentId",userId);
            paramMap.put("status02","02");
            paramMap.put("status03","03");
            paramMap.put("status06","06");
            List<RepaireInfo> repaireInfoList = repaireInfoService.searchRepaireInfoForCustom(paramMap);
            repaireInfoList.forEach(info ->{
                info.setStatus(Constants.getStatus(info.getStatus()));
                info.setAddress(Constants.getAddress(info.getAddress()));
            });
            model.addAttribute("repaireInfos",repaireInfoList);
            model.addAttribute("userId",userId);
            return "customService/allocation_repair";
//        }
//        model.addAttribute("msg","您没有权限操作！");
//        return "warn";
    }


    public boolean validateAuth(String userId,Integer roleId){
        Map<String,String> params = new HashedMap();
        params.put("userName",userId);
        User user = userService.findOne(params);
        Optional<User> optional = Optional.ofNullable(user);
        if(optional.isPresent()){
            if(roleId == optional.get().getRoleId()){
                return true;
            }
        }
        return false;
    }

    @RequestMapping(value = "/engineer" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> findEngineer(HttpServletRequest request){
        String userId = WXUserUtil.findCookie(request);
        User  user = new User();
        user.setEnabled(true);
        List<User> users = userService.listByAllocation(user);
        List<PickerVO> pickerVOS = new ArrayList<>();
        users.forEach(user_out ->{
            // 排除当前用户  工程师转单使用
            if(!userId.equals(user_out.getUserName())){
                PickerVO vo =  new PickerVO();
                vo.setLabel(user_out.getDisplayName());
                vo.setValue(user_out.getUserName());
                pickerVOS.add(vo);
            }
        });
        Map<String,Object> result = getSuccessResult();
        result.put(ResponseData.DATA,pickerVOS);
        return result;
    }

    @RequestMapping(value = "/update" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> update01(RepaireInfo repaireInfo,HttpServletRequest request){
        String userId = WXUserUtil.findCookie(request);
        Map<String ,String> maps = new HashedMap();
        maps.put("userName",userId);
        User user = userService.findOne(maps);
        repaireInfo.setStatus("06");
        repaireInfo.setAllocationer(user.getDisplayName()); //将调配者插入数据库
        repaireInfoService.update(repaireInfo);
        //  微信端提醒
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.ENGINEER_AGENT_ID);
        wxMsg.setMsgtype("textcard");
        wxMsg.setTouser(repaireInfo.getCurrentId());
        Textcard textcard = new Textcard();
        textcard.setTitle("任务来了");
        textcard.setDescription("您来了一个新任务 请点击查收");
        textcard.setUrl(WxepConstants.ENGINEER_MODIFY_URL);
        wxMsg.setTextcard(textcard);
        try {
            weixinNotifyService.sendMsg(wxMsg,WxepConstants.ENGINEER_SECRET);
        } catch (Exception e) {
            log.error("weixinNotifyService.sendMsg error|",e);
        }
        return getSuccessResult();
    }

}
